package com.example.lexiangbackend.service;

import com.example.lexiangbackend.entity.User;
import com.example.lexiangbackend.entity.Music;
import com.example.lexiangbackend.entity.PlayHistory;
import com.example.lexiangbackend.entity.Favorite;
import com.example.lexiangbackend.repository.UserRepository;
import com.example.lexiangbackend.repository.MusicRepository;
import com.example.lexiangbackend.repository.PlayHistoryRepository;
import com.example.lexiangbackend.repository.FavoriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private MusicRepository musicRepository;
    
    @Autowired
    private PlayHistoryRepository playHistoryRepository;
    
    @Autowired
    private FavoriteRepository favoriteRepository;

    /**
     * 根据ID获取用户
     */
    public User getUserById(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    /**
     * 获取所有用户
     */
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    /**
     * 删除用户
     */
    public void deleteUser(Long userId) {
        if (!userRepository.existsById(userId)) {
            throw new RuntimeException("用户不存在");
        }
        
        // TODO: 删除用户相关的数据（收藏、播放历史等）
        // 或者可以设置为软删除
        
        userRepository.deleteById(userId);
    }

    /**
     * 根据用户名查找用户
     */
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    /**
     * 根据邮箱查找用户
     */
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    /**
     * 根据手机号查找用户
     */
    public Optional<User> findByPhoneNumber(String phoneNumber) {
        // TODO: 需要在UserRepository中添加此方法
        return Optional.empty();
    }

    /**
     * 更新用户信息
     */
    public User updateUser(User user) {
        return userRepository.save(user);
    }

    /**
     * 获取用户总数
     */
    public long getUserCount() {
        return userRepository.count();
    }

    /**
     * 搜索用户
     */
    public List<User> searchUsers(String keyword) {
        // TODO: 需要在UserRepository中添加此方法
        return userRepository.findAll();
    }

    /**
     * 检查用户是否存在
     */
    public boolean existsById(Long userId) {
        return userRepository.existsById(userId);
    }

    /**
     * 更新用户信息（管理员用）
     */
    public User updateUser(Long userId, Map<String, Object> updateData) {
        User user = getUserById(userId);
        
        // 更新允许修改的字段
        if (updateData.containsKey("username")) {
            String username = (String) updateData.get("username");
            if (username != null && !username.trim().isEmpty()) {
                // 检查用户名是否已被其他用户使用
                Optional<User> existingUser = userRepository.findByUsername(username);
                if (existingUser.isPresent() && !existingUser.get().getUserId().equals(userId)) {
                    throw new RuntimeException("用户名已被使用");
                }
                user.setUsername(username.trim());
            }
        }
        
        if (updateData.containsKey("email")) {
            String email = (String) updateData.get("email");
            if (email != null && !email.trim().isEmpty()) {
                // 检查邮箱是否已被其他用户使用
                Optional<User> existingUser = userRepository.findByEmail(email);
                if (existingUser.isPresent() && !existingUser.get().getUserId().equals(userId)) {
                    throw new RuntimeException("邮箱已被使用");
                }
                user.setEmail(email.trim());
            }
        }
        
        if (updateData.containsKey("phone")) {
            String phone = (String) updateData.get("phone");
            if (phone != null && !phone.trim().isEmpty()) {
                user.setPhone(phone.trim());
            }
        }
        
        if (updateData.containsKey("status")) {
            Integer status = (Integer) updateData.get("status");
            if (status != null) {
                user.setStatus(status);
            }
        }
        
        return userRepository.save(user);
    }

    /**
     * 批量删除用户
     */
    public void batchDeleteUsers(List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return;
        }
        
        // 检查所有用户ID是否存在
        for (Long userId : userIds) {
            if (!userRepository.existsById(userId)) {
                throw new RuntimeException("用户ID " + userId + " 不存在");
            }
        }
        
        // TODO: 删除用户相关的数据（收藏、播放历史等）
        // 或者可以设置为软删除
        
        userRepository.deleteAllById(userIds);
    }

    /**
     * 批量更新用户状态
     */
    public void batchUpdateUserStatus(List<Long> userIds, Integer status) {
        if (userIds == null || userIds.isEmpty()) {
            return;
        }
        
        if (status == null || (status != 0 && status != 1)) {
            throw new RuntimeException("状态值无效，必须为0（正常）或1（锁定）");
        }
        
        // 检查所有用户ID是否存在，并批量更新状态
        for (Long userId : userIds) {
            User user = userRepository.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户ID " + userId + " 不存在"));
            user.setStatus(status);
            userRepository.save(user);
        }
    }

    /**
     * 添加播放历史
     */
    public PlayHistory addPlayHistory(Long userId, Long musicId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Music music = musicRepository.findById(musicId)
                .orElseThrow(() -> new RuntimeException("音乐不存在"));
        
        // 增加音乐播放量
        music.incrementPlayCount();
        musicRepository.save(music);
        
        PlayHistory playHistory = new PlayHistory(user, music);
        return playHistoryRepository.save(playHistory);
    }

    /**
     * 获取播放历史
     */
    public Page<PlayHistory> getPlayHistory(Long userId, Pageable pageable) {
        return playHistoryRepository.findByUserUserIdOrderByPlayTimeDesc(userId, pageable);
    }

    /**
     * 添加收藏
     */
    public Favorite addFavorite(Long userId, Long musicId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Music music = musicRepository.findById(musicId)
                .orElseThrow(() -> new RuntimeException("音乐不存在"));
        
        // 检查是否已经收藏
        if (favoriteRepository.existsByUserUserIdAndMusicMusicId(userId, musicId)) {
            throw new RuntimeException("已经收藏过这首歌");
        }
        
        Favorite favorite = new Favorite(user, music);
        return favoriteRepository.save(favorite);
    }

    /**
     * 取消收藏
     */
    public void removeFavorite(Long userId, Long musicId) {
        Optional<Favorite> favorite = favoriteRepository.findByUserUserIdAndMusicMusicId(userId, musicId);
        if (favorite.isPresent()) {
            favoriteRepository.delete(favorite.get());
        } else {
            throw new RuntimeException("收藏记录不存在");
        }
    }

    /**
     * 获取收藏列表
     */
    public Page<Favorite> getFavorites(Long userId, Pageable pageable) {
        return favoriteRepository.findByUserUserId(userId, pageable);
    }

    /**
     * 检查是否已收藏
     */
    public boolean isFavorite(Long userId, Long musicId) {
        return favoriteRepository.existsByUserUserIdAndMusicMusicId(userId, musicId);
    }
} 